/// 本文件由reazhuang@outlook.com开发编写 *CodeMaid自动格式化*
///设计为一个开关
///只能绑定布尔型单选
///具有开/关两个状态
///如果是空值视为关

using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;

namespace ReaWTM.LayuiHelper
{
	[HtmlTargetElement("wt:switch", Attributes = REQUIRED_ATTR_NAME, TagStructure = TagStructure.WithoutEndTag)]
	public class SwitchTagHelper : BaseFieldTag
	{
		private Type _modelType;
		public string ChangeFunc { get; set; }
		public new bool DefaultValue { get; set; }
		public string OffText { get; set; } = CoreProgram._localizer?["Sys.No"];
		public string OnText { get; set; } = CoreProgram._localizer?["Sys.Yes"];

		public override void Process(TagHelperContext context, TagHelperOutput output)
		{
			_modelType = Field.Metadata.ModelType;
			if (!_modelType.IsBoolOrNullableBool())
			{
				throw new Exception("wt:switch只能绑定布尔型");
			}

			output.TagName = "input";
			output.TagMode = TagMode.StartTagOnly;
			output.Attributes.Add("type", "checkbox");
			output.Attributes.Add("lay-skin", "switch");
			output.Attributes.Add("value", "true");
			output.Attributes.Add("lay-text", $"{OnText}|{OffText}");

			if (GetDefaultValue())
			{
				output.Attributes.Add("checked", null);
			}
			output.PostElement.AppendHtml($@"
<script>
wtm.switch_Render({{
id:'{Id}',
changeFunc:'{ChangeFunc}',
beforeMount:'{BeforeMount}',
mounted:'{Mounted}',
}});
</script>");
			base.Process(context, output);
		}

		private bool GetDefaultValue()
		{
			if (Field.Model != null)
			{
				DefaultValue = (bool)Field.Model;
			}

			return DefaultValue;
		}
	}
}